package com.mgq.juc.reentrantLock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

import static java.lang.Thread.sleep;

/**
 * @author MaGuangQi
 * synchronized 不能被打断
 * @date 2021-12-16 17:02
 **/
@Slf4j
public class TestReentrantLock {
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            synchronized (TestReentrantLock.class) {
                log.debug("t1线程获得锁");
                while (true) {

                }
            }

        }, "t1");
       // t1.start();
        //无法打断 synchronized
        //主线程先获取锁
        /*synchronized (TestReentrantLock.class) {
            log.debug("主线程获得锁");
            log.debug("打断t1");
            t1.interrupt();
            sleep(5000);
        }*/



        ReentrantLock lock = new ReentrantLock();
        Thread t3 = new Thread(() -> {
            //lock 无法被打断
           // lock.lock();
            try {
                //如果有竞争,进入阻塞队列,可以被其他线程打断
                lock.lockInterruptibly();
                lock.lock();
            } catch (InterruptedException e) {
                log.debug("被打断了,没有获得锁");
                e.printStackTrace();
                return;
            }
            try {
                log.debug("获取到锁");
            } finally {
                lock.unlock();
            }


        }, "t3");
        t3.start();
        lock.lock();
        sleep(1000);
        t3.interrupt();
    }
}
